package com.omni.monitor.plugin.utils;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


@Component
// 前缀要匹配 YML 中的 "trace-monitor"
@ConfigurationProperties(prefix = "trace-monitor")
@Data
public class MonitorConfig {

    @Value("${trace-monitor.pointcut_packages}")
    private String pointcut_packages;
    @Value("${trace-monitor.exclude_service_method}")
    private String exclude_service_method;
    @Value("${trace-monitor.project_package}")
    private String project_package;
    @Value("${trace-monitor.project_sourceRoot}")
    private String project_sourceRoot;
    /**
     * 监控是否开启  on: 开启  off: 关闭
     */
    @Value("${trace-monitor.enabled}")
    private String enabled;
    @Value("${trace-monitor.parameterSwitch}")
    private String parameterSwitch;
    @Value("${trace-monitor.esIndexName}")
    private String esIndexName;
    /**
     * esToken
     */
    @Value("${trace-monitor.esToken}")
    private String esToken;
    /**
     * ES地址
     */
    @Value("${trace-monitor.esURL}")
    private String esURL;
    /**
     * 线程池配置（映射omni-thread-pool子层级）
     */
    private OmniThreadPool omniThreadPool = new OmniThreadPool(); // 初始化避免空指针


    /**
     * 嵌套类：映射omni-thread-pool子配置
     */
    @Data
    public static class OmniThreadPool {
        /**
         * 核心线程数目
         */
        private int corePoolSize=0;

        /**
         * 最大线程数
         */
        private int maxPoolSize=0;

        /**
         * 队列中最大的数目
         */
        private int queueCapacity=0;

        /**
         * 线程名称前缀
         */
        private String threadNamePrefix="Omni";

        /**
         * 线程空闲后的最大存活时间（秒）
         */
        private int keepAliveSeconds=20;
    }




    // @Bean
    public String pointcutExpression() {
        return buildPointcutExpression(pointcut_packages);
    }

    private String buildPointcutExpression(String packages) {
        if (StringUtils.isEmpty(packages)) {
            return "";
        }

        String[] packageArray = packages.split(",");
        StringBuilder expression = new StringBuilder();

        for (int i = 0; i < packageArray.length; i++) {
            if (i > 0) {
                expression.append(" || ");
            }
            expression.append("execution(* ").append(packageArray[i].trim()).append("..*(..))");
        }

        return expression.toString();
    }
}
